package org.example.demo1.service;

import lombok.extern.slf4j.Slf4j;
import org.example.demo1.Entity.SolutionFeedback;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class FeedbackCollectionService {

    @Autowired
    private VectorStore vectorStore;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String FEEDBACK_PREFIX = "feedback:";
    private static final long FEEDBACK_EXPIRE_HOURS = 24;
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 记录AI回答，等待用户反馈
     */
    public String recordAIResponse(String sessionId, String userQuestion, String aiResponse, List<String> toolsCalled) {
        String feedbackId = UUID.randomUUID().toString();

        // 使用Map存储，避免序列化问题
        Map<String, Object> feedbackData = new HashMap<>();
        feedbackData.put("id", feedbackId);
        feedbackData.put("sessionId", sessionId);
        feedbackData.put("userQuestion", userQuestion);
        feedbackData.put("aiResponse", aiResponse);
        feedbackData.put("toolsCalled", toolsCalled != null ? toolsCalled : new ArrayList<>());
        feedbackData.put("problemCategory", categorizeProblem(userQuestion, aiResponse));
        feedbackData.put("timestamp", LocalDateTime.now().format(FORMATTER));

        // 存储到Redis
        String key = FEEDBACK_PREFIX + feedbackId;
        redisTemplate.opsForValue().set(key, feedbackData, FEEDBACK_EXPIRE_HOURS, TimeUnit.HOURS);

        log.info("记录AI回答等待反馈: {} - {}", feedbackId, feedbackData.get("problemCategory"));
        return feedbackId;
    }

    /**
     * 处理用户反馈
     */
    public String processFeedback(String feedbackId, boolean isEffective, String userComment) {
        String key = FEEDBACK_PREFIX + feedbackId;
        Map<String, Object> feedbackData = (Map<String, Object>) redisTemplate.opsForValue().get(key);

        if (feedbackData == null) {
            return "❌ 反馈已过期或不存在，请重新提问";
        }

        feedbackData.put("isEffective", isEffective);
        feedbackData.put("userFeedback", userComment);

        if (isEffective) {
            // 解决方案有效，存入向量数据库
            return processEffectiveSolution(feedbackData);
        } else {
            // 记录失败案例
            log.info("用户反馈解决方案无效: {} - {}", feedbackData.get("problemCategory"), userComment);
            return "感谢您的反馈！我们会分析失败原因，持续改进解决方案。";
        }
    }

    /**
     * 处理有效解决方案 - 存入向量数据库
     */
    private String processEffectiveSolution(Map<String, Object> feedbackData) {
        try {
            // 构建知识文档
            String knowledgeText = buildKnowledgeDocument(feedbackData);

            // 创建Document并添加元数据
            Document document = new Document(knowledgeText);
            document.getMetadata().put("type", "solution");
            document.getMetadata().put("category", (String) feedbackData.get("problemCategory"));
            document.getMetadata().put("timestamp", (String) feedbackData.get("timestamp"));

            List<String> toolsCalled = (List<String>) feedbackData.get("toolsCalled");
            if (toolsCalled != null && !toolsCalled.isEmpty()) {
                document.getMetadata().put("tools_used", String.join(",", toolsCalled));
            }
            document.getMetadata().put("session_id", (String) feedbackData.get("sessionId"));

            // 存入向量数据库
            vectorStore.add(List.of(document));

            log.info("成功将有效解决方案添加到知识库: {}", feedbackData.get("problemCategory"));

            return String.format("""
                ✅ **感谢您的反馈！**
                
                您的成功案例已自动添加到知识库：
                - 问题类型: %s
                - 使用工具: %s
                - 存储时间: %s
                
                这将帮助改进未来相似问题的解决效率！
                """,
                    feedbackData.get("problemCategory"),
                    toolsCalled != null ? String.join(", ", toolsCalled) : "无",
                    feedbackData.get("timestamp")
            );

        } catch (Exception e) {
            log.error("处理有效解决方案失败: {}", e.getMessage(), e);
            return "❌ 存储解决方案时出错，但您的反馈已记录";
        }
    }

    /**
     * 构建知识文档文本
     */
    private String buildKnowledgeDocument(Map<String, Object> feedbackData) {
        StringBuilder doc = new StringBuilder();

        doc.append("# ").append(feedbackData.get("problemCategory")).append("解决方案\n\n");

        doc.append("## 问题描述\n");
        doc.append(feedbackData.get("userQuestion")).append("\n\n");

        doc.append("## 解决方案\n");
        doc.append(feedbackData.get("aiResponse")).append("\n\n");

        List<String> toolsCalled = (List<String>) feedbackData.get("toolsCalled");
        if (toolsCalled != null && !toolsCalled.isEmpty()) {
            doc.append("## 使用的诊断工具\n");
            for (String tool : toolsCalled) {
                doc.append("- ").append(tool).append("\n");
            }
            doc.append("\n");
        }

        String userFeedback = (String) feedbackData.get("userFeedback");
        if (userFeedback != null && !userFeedback.trim().isEmpty()) {
            doc.append("## 用户反馈\n");
            doc.append(userFeedback).append("\n\n");
        }

        doc.append("## 元信息\n");
        doc.append("- 解决时间: ").append(feedbackData.get("timestamp")).append("\n");
        doc.append("- 问题分类: ").append(feedbackData.get("problemCategory")).append("\n");
        doc.append("- 验证状态: 用户确认有效\n");

        return doc.toString();
    }

    /**
     * 自动分类问题
     */
    private String categorizeProblem(String question, String response) {
        String text = (question + " " + response).toLowerCase();

        if (text.contains("cpu") || text.contains("stresschaos")) {
            return "CPU压力问题";
        } else if (text.contains("crash") || text.contains("crashloopbackoff") || text.contains("podchaos")) {
            return "Pod崩溃问题";
        } else if (text.contains("内存") || text.contains("memory") || text.contains("oom")) {
            return "内存问题";
        } else if (text.contains("网络") || text.contains("network")) {
            return "网络问题";
        } else if (text.contains("存储") || text.contains("volume") || text.contains("pvc")) {
            return "存储问题";
        } else {
            return "Kubernetes通用问题";
        }
    }
}
